
<section class="content-header">
    <h1>&nbsp;</h1>
    <ol class="breadcrumb">
        <li><a href="#"><i class="fa fa-dashboard"></i>信息管理</a></li>
        <li class="active"><a href="#">角色管理</a></li>
    </ol>
</section>
<!-- Main content -->
<section class="content" id="deviceContent">
    <div class="row">
        <div class="col-xs-12">
            <div class="box">
                <div class="box-body">
                    <!-- 搜索条件 -->
                    <table class="table">
                        <tr height="45px" bgcolor="#F3F3F3">
                            <td align="left"><button
                                    class="btn btn-danger btn-small" data-toggle="modal" onclick="showadddialog();">添加父菜单</button></td>
                        </tr>
                    </table>
                    <!-- 结果列表 -->
                    <table id="myTableData"
                           class="table table-bordered table-condensed table-hover table-striped">
                        <thead>
                        <tr>
                            <th>ID</th>
                            <th>序号</th>
                            <th>菜单名称</th>
                            <th>module</th>
                            <th>subModule</th>
                            <th>类型</th>
                            <th>父菜单</th>
                            <th>操作</th>
                        </tr>
                        </thead>
                        <tbody class="j-menu-tbody">
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</section>

<script type="application/template" id="j-module-tpl">
    <div class="modal fade" id="modal-default">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title j-modal-title"></h4>
                </div>
                <div class="modal-body">

                    <form class="form-horizontal" id="defaultForm">
                        <div class="box-body">
                            <div class="form-group">
                                <label for="menuName" class="col-sm-2 control-label">菜单名称</label>
                                <div class="col-sm-9">
                                    <input type="text" class="form-control hidden" id="menuid" value="-1">
                                    <input type="text" class="form-control hidden" id="parentid" value="">
                                    <input type="text" class="form-control" id="menuName" name="menuName" placeholder="">
                                </div>
                                <div class="col-sm-1">
                                    <span class="promptMsg">*</span>
                                </div>
                            </div>
                            <div class="form-group j-module-div">
                                <label for="module" class="col-sm-2 control-label">菜单英文</label>
                                <div class="col-sm-9">
                                    <input type="text" class="form-control" id="module" name="module" placeholder="">
                                </div>
                                <div class="col-sm-1">
                                    <span class="promptMsg">*</span>
                                </div>
                            </div>
                            <div class="form-group j-subModule-div">
                                <label for="subModule" class="col-sm-2 control-label">菜单英文</label>
                                <div class="col-sm-9">
                                    <input type="text" class="form-control" id="subModule" name="subModule" placeholder="" disabled>
                                </div>
                                <div class="col-sm-1">
                                    <span class="promptMsg">*</span>
                                </div>
                            </div>
                            <div class="form-group j-type-div">
                                <label for="subModule" class="col-sm-2 control-label">菜单类型</label>
                                <div class="col-sm-9">
                                    <select class="form-control j-type-select">
                                        <option value="0" selected>后台菜单</option>
                                        <option value="1">前端菜单</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                    </form>

                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary" onclick="saverole();">保存</button>
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                </div>
            </div>
        </div>
    </div>
</script>
<script>

    $(function(){
        var oTable = $("#myTableData").dataTable({
            lengthMenu: [10],//这里也可以设置分页，但是不能设置具体内容，只能是一维或二维数组的方式，所以推荐下面language里面的写法。
            paging: true,//分页
            ordering: true,//是否启用排序
            searching: false,//搜索
            language: {
                lengthMenu: '',//左上角的分页大小显示。
                paginate: {//分页的样式内容。
                    previous: "上一页",
                    next: "下一页",
                    first: "首页",
                    last: "末页"
                },
                zeroRecords: "没有内容",//table tbody内容为空时，tbody的内容。
                //下面三者构成了总体的左下角的内容。
                info: "总共_PAGES_ 页，显示第_START_ 到第 _END_条记录 ，记录总数： _TOTAL_条 ",//左下角的信息显示，大写的词为关键字。
                infoEmpty: "0条记录",//筛选为空时左下角的显示。
                infoFiltered: ""//筛选之后的左下角筛选提示，
            },
            pagingType: "full_numbers",//分页样式的类型
            "serverSide": true,
            ajax: function (data, callback, settings) {
                //封装请求参数
                var param = {};
                param.limit = data.length;//页面显示记录条数，在页面显示每页显示多少项的时候
                param.start = data.start;//开始的记录序号
                param.page = (data.start / data.length)+1;//当前页码
                param.orderby=data.orderBys;
                //ajax请求数据
                $.ajax({
                    type: "get",
                    url: "${request.contextPath}/menu/",
                    cache: false,  //禁用缓存
                    data: param,  //传入组装的参数
                    dataType: "json",
                    headers: {
                        Accept: "application/json   "
                    },
                    contentType: 'application/json;charset=utf-8',
                    success: function (result) {

                        //封装返回数据
                        var returnData = {};
                        returnData.draw = data.draw;//这里直接自行返回了draw计数器,应该由后台返回
                        returnData.recordsTotal = result.total;//返回数据全部记录
                        returnData.recordsFiltered = result.total;//后台不实现过滤功能，每次查询均视作全部结果
                        returnData.data = result.pageData;//返回的数据列表
                        //调用DataTables提供的callback方法，代表数据已封装完成并传回DataTables进行渲染
                        //此时的数据需确保正确无误，异常判断应在执行此回调前自行处理完毕
                        callback(returnData);
                        $('.j-menu-tbody').sortable({
                            items:"tr[role='row']",
                            activate:function( event, ui ){
                                $(" tbody .j-look-childmenu").trigger('click',[true])
                            },
                            stop: function( event, ui ) {
                                var arr = [];
                                var ids = $("#myTableData button.j-parent-menu-id");
                                $.each(ids,function(i,item){
                                    var id = $(item).attr("data-menu-id");
                                    arr.push(Number(id))
                                });
                                $.ajax({
                                    url : "${request.contextPath}/order/menu/",
                                    type : "PATCH",
                                    data : JSON.stringify(arr),
                                    headers:{
                                        Accept:'application/json'
                                    },
                                    contentType:'application/json',
                                    success : function(s) {
                                            location.reload();
                                    }
                                });
                            }
                        });
                    }
                });
            },
            //列表表头字段
            columns: [
                { "data": "id" },
                { "data": null },
                { "data": "name" },
                { "data": "module" },
                { "data": "subModule" },
                { "data": null },
                { "data": null},
                { "data": null}
            ],
            fnDrawCallback  : function(){
                this.api().column(1).nodes().each(function(cell, i) {
                    cell.innerHTML =  i + 1;
                });
            },
            "aoColumnDefs":[
                {
                    "targets":0,
                    "visible":false
                },
                {//倒数第一列
                    "targets":1,
                    "bSortable": false,
                    render: function(data, type, row,meta ) {
                        return "";
                    }
                },
                {//倒数第一列
                    "targets":-1,
                    "bSortable": false,
                    render: function(data, type, row) {
                        var isParent = 0;
                        if(data.parentMenu){
                            isParent = 1;
                        }
                        var html ='<button class="btn btn-success btn-small j-look-childmenu" >查看子菜单</button>&nbsp;&nbsp;&nbsp;&nbsp;<button data-menu-id="'+data.id+'" class="btn btn-success btn-small j-menu-id j-parent-menu-id" onclick="showeditdialog(\''+data.id+'\',\''+data.name+'\',\''+data.module+'\',\''+data.subModule+'\','+isParent+','+data.type+');">编辑</button>'
                            +'&nbsp;&nbsp;&nbsp;&nbsp;<button class="btn btn-danger btn-small" onclick="delMenu(\''+data.id+'\');">删除</button>';
                        if(!data.parentMenu){
                            html += '&nbsp;&nbsp;&nbsp;&nbsp;<button class="btn btn-success btn-small" onclick="addChilddialog('+data.id+','+data.type+')">添加子菜单</button>';
                        }
                        return html;
                    }
                },
                {//倒数第一列
                    "targets":-2,
                    "bSortable": false,
                    render: function(data, type, row) {
                        var html = "";
                        if(data.parentMenu){
                           html =data.parentMenu.name;
                        }
                        return html;
                    }
                },
                {//倒数第一列
                    "targets":-3,
                    "bSortable": false,
                    render: function(data, type, row) {
                        var html = "前台菜单";
                        if(data.type == "0"){
                            html="后台菜单";
                        }
                        return html;
                    }
                },
            ]
        });
        $('.table').on('click', ' tbody .j-look-childmenu',
            function(event,status) {
                var status = status || false;
                var nTr = $(this).parents('tr')[0];
                if (status || oTable.fnIsOpen(nTr)) //判断是否已打开
                {
                    $(this).addClass("row-details-close").removeClass("row-details-open");
                    oTable.fnClose(nTr);
                } else {
                    $(this).addClass("row-details-open").removeClass("row-details-close");
                    fnFormatDetails(nTr, $(this).attr("data_id"));
                }
            });
        function fnFormatDetails(nTr, pdataId) {
            var parentId = Number($(nTr).find(".j-menu-id").attr('data-menu-id'));
            $.ajax({
                url : "${request.contextPath}/parentid/"+parentId+"/menu/",
                type : "get",
                data : null,
                headers:{
                    Accept:'application/json'
                },
                contentType:'application/json',
                success : function(result) {
                    var menuStr = "";
                    $.each(result,function(i,menu){
                        var isParent = 0;
                        if(menu.parentMenu){
                            isParent = 1;
                        }
                        menuStr +=  '<tr class = "j-child-tr">\n' +
                                        '<td>'+menu.name+'</td>\n' +
                                        '<td>'+menu.subModule+'</td>\n' +
                                        '<td><button data-menu-id="'+menu.id+'" class="btn btn-success btn-small j-menu-id" onclick="showeditdialog(\''+menu.id+'\',\''+menu.name+'\',\''+menu.module+'\',\''+menu.subModule+'\','+isParent+','+menu.type+');">编辑</button>\n' +
                                  '&nbsp;&nbsp;&nbsp;&nbsp;<button class="btn btn-danger btn-small" onclick="delMenu(\''+menu.id+'\');">删除</button></td>'+
                                    '</tr>\n';
                    });
                    var childtable = "";
                    if(menuStr != ""){
                        childtable=  '<div style="margin:0 40px 0px 20px"><table class="table table-bordered" data-parent-id="'+parentId+'">\n' +
                            '                <tbody><tr>\n' +
                            '                  <th>子菜单</th>\n' +
                            '                  <th>subModule</th>\n' +
                            '                  <th >操作</th>\n' +
                            '                </tr>\n' +menuStr+
                            '              </tbody></table></div>';
                    }
                    var obj = $(childtable);
                    obj.find("tbody").sortable({
                        items:"tr.j-child-tr",
                        stop: function( event, ui ) {
                            var arr = [];
                            var ids = obj.find("button.j-menu-id");
                            $.each(ids,function(i,item){
                                var id = $(item).attr("data-menu-id");
                                arr.push(Number(id));
                            });
                            $.ajax({
                                url : "${request.contextPath}/order/parent/"+parentId+"/menu/",
                                type : "PATCH",
                                data : JSON.stringify(arr),
                                headers:{
                                    Accept:'application/json'
                                },
                                contentType:'application/json',
                                success : function(s) {
                                    location.reload();
                                }
                            });
                        }
                    });
                    oTable.fnOpen(nTr,obj , 'details j-child-menu-details');
                }
            });


        }
    });

    function validator(obj){
        obj.bootstrapValidator({
            message: '此值无效',
            feedbackIcons: {
                valid: 'glyphicon glyphicon-ok',
                invalid: 'glyphicon glyphicon-remove',
                validating: 'glyphicon glyphicon-refresh'
            },
            fields: {
                menuName: {
                    validators: {
                        notEmpty: {
                            message: '菜单名称不能为空'
                        },
                        stringLength: {
                            min: 1,
                            max: 20,
                            message: '菜单名必须大于0，长度小于6个字符'
                        }
                    }
                },
                module: {
                    validators: {
                        notEmpty: {
                            message: '英文名称不能为空'
                        },
                        stringLength: {
                            min: 1,
                            max: 20,
                            message: '英文名称必须大于0，长度小于20个字符'
                        }
                    }
                },
                subModule: {
                    validators: {
                        notEmpty: {
                            message: '英文名称'
                        },
                        stringLength: {
                            min: 1,
                            max: 20,
                            message: '英文名称必须大于0，长度小于20个字符'
                        }
                    }
                }
            }
        });
    }

    function isExist4Modal(){
        $("#modal-default").remove();
    }

    function addChilddialog(id,type) {
        isExist4Modal();
        var html = $("#j-module-tpl").html();
        var obj = $(html);
        obj.find(".j-modal-title").text("添加子菜单");
        obj.find("#menuid").val("-2");

        obj.find("#parentid").val(id);
        obj.find(".j-module-div").css("display","none");
        obj.find("#subModule").removeAttr("disabled");
        obj.find(".j-type-select").val(type);
        obj.find(".j-type-select").attr("disabled",true);
        validator(obj.find("#defaultForm"));
        obj.modal('show');
    }

    function showadddialog()
    {
        isExist4Modal();
        var html = $("#j-module-tpl").html();
        var obj = $(html);
        obj.find(".j-modal-title").text("添加父菜单");
        obj.find("#menuid").val("-1");
        obj.find(".j-subModule-div").css("display","none");
        validator(obj.find("#defaultForm"));
        obj.modal('show');
    }

    function showeditdialog(id,name,module,subModule,isParent,type)
    {
        isExist4Modal();
        var html = $("#j-module-tpl").html();
        var obj = $(html);
        obj.find(".j-modal-title").text("编辑菜单");
        obj.find("#menuid").val(id);
        obj.find("#menuName").val(name);
        obj.find("#module").val(module);
        obj.find(".j-type-select").val(type);
        obj.find(".j-type-select").attr("disabled",true);
        if(isParent == "1") {
            obj.find("#subModule").val(subModule);
            obj.find("#subModule").removeAttr("disabled");
            obj.find(".j-module-div").css("display","none");
        }else{
            obj.find(".j-subModule-div").css("display","none");
        }
        validator(obj.find("#defaultForm"));
        obj.modal('show');
    }


    function delMenu(id)
    {
        CvMsg.confirm("警告","确定要删除？",function(){
            $.ajax({
                url : "${request.contextPath}/menu/"+id,
                type : "delete",
                data : null,
                headers:{
                    Accept:'application/json'
                },
                contentType:'application/json',
                success : function(s) {
                    if (s.success) {
                        location.reload();
                    } else {
                        alert(s.msg);
                    }
                }
            });
        });

    }

    function saverole()
    {
        var bootstrapValidator = $('#defaultForm').data('bootstrapValidator');
        bootstrapValidator.validate();
        if(!bootstrapValidator.isValid()){
           return;
        }
        var menuid = $("#menuid").val();
        var menuName = $("#menuName").val();
        var module = $("#module").val();
        var subModule = $("#subModule").val();
        var type = $(".j-type-select").val();
        if (menuid == -1)
        {
            CvMsg.confirm("提示","确定要添加？",function(){
                var data = {name:menuName,module:module,subModule:subModule,type:type};
                debugger;
                $.ajax({
                    url : "${request.contextPath}/menu",
                    type : "post",
                    headers:{
                        Accept:'application/json'
                    },
                    contentType:'application/json',
                    data : JSON.stringify(data),
                    success : function(s) {
                        if (s.success) {
                            location.reload();
                        } else {
                            alert(s.msg);
                        }
                    }
                });
            });
        }
        else if(menuid == -2 ){
            CvMsg.confirm("提示","确定要添加？",function(){
                var parentid = $("#parentid").val();
                var data = {name:menuName,module:module,subModule:subModule,type:type};
                $.ajax({
                    url : "${request.contextPath}/parent/"+parentid+"/menu/",
                    type : "post",
                    headers:{
                        Accept:'application/json'
                    },
                    contentType:'application/json',
                    data : JSON.stringify(data),
                    success : function(s) {
                        if (s.success) {
                            location.reload();
                        } else {
                            alert(s.msg);
                        }
                    }
                });
            });
        }
        else
        {
            CvMsg.confirm("提示","确定要修改？",function(){
                var data = {id:menuid,name:menuName,module:module,subModule:subModule,type:type};
                $.ajax({
                    url : "${request.contextPath}/menu/"+menuid,
                    type : "put",
                    data : JSON.stringify(data),
                    headers:{
                        Accept:'application/json'
                    },
                    contentType:'application/json',
                    success : function(s) {
                        if (s.success) {
                            location.reload();
                        } else {
                            alert(s.msg);
                        }
                    }
                });
            });
        }
    }


</script>